package com.shop.user.mqHandler.sentMessage;

import com.shop.ex.ShoppingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author 'banxia'
 * @version 1.0
 * @description 用于发送消息到死信交换机！
 * @date 2023/2/28 13:54
 */
@Component
@Slf4j
public class OrderCancelHandler {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //该方法专门用来发送订单取消的消息
    //发送消息（提供接口）
    public void sendToExchange(String message){
        if (Strings.isEmpty(message)){
            ShoppingException.ThrowShoppingException("消息不可以为空");
        }
        String exchangeName="ttl.direct";
        //1、准备消息
        Message msg = MessageBuilder
                .withBody(message.getBytes(StandardCharsets.UTF_8))
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT) //（设置消息超时时间，持久化）
                .build();
        //2、发送消息
        rabbitTemplate.convertAndSend(exchangeName,"ttl",msg);
        log.debug("消息发送成功");
    }

}
